import 'package:get/get.dart';
import 'package:xin_he/page/mine/xin_he_bank_management/xin_he_bank_entity.dart';

import '../../../service/xin_he_reqest.dart';
import '../../../utils/xin_he_event_bus.dart';
import '../../../utils/xin_he_storage.dart';
import '../../../utils/xin_he_toast.dart';
import 'xin_he_bank_management_state.dart';

class XinHeBankManagementLogic extends GetxController {
  final XinHeBankManagementState state = XinHeBankManagementState();

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
  }

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();

    requestBanksInfo();
  }

  requestBanksInfo() async{

    var userId =  await XinHeLocalStorage.get(XinHeStorage.userId);

    Map<String,dynamic>map = {
      // 'orderStatus':type,
      'userId':userId
    };
    XinHeRequestDataResult result = await XinHeHttpRequestData.requestUniversalPost(url: '/bankCard/queryBankCard',params: map,isPost: false);

    if(!result.result|| result.data['code'] != 0){
      XinHeToast.center(result.data['message']);
      return ;
    }
    List list = result.data['data'] ??[];
    List items = [];
    if(list.isNotEmpty){
      for(int i = 0; i< list.length; i++){
          XinHeBankEntity model = XinHeBankEntity.fromJson(list[i]);
          if(model.isDefault != null && model.isDefault == 1){
            state.selectedIndex.value = i;
          }
          items.add(model);
      }
      state.list.value = items;
    }else {
      state.list.clear();
    }
  }


  deleteItem(int id) async{
    Map<String,dynamic>map = {
      'bankCardId':id
    };
    XinHeRequestDataResult result = await XinHeHttpRequestData.requestUniversalPost(url: '/bankCard/deleteBankCard',params: map,isPost: false);

    if(!result.result|| result.data['code'] != 0){
      XinHeToast.center(result.data['message']);
      return ;
    }
    XinHeToast.center('删除成功');
    refreshData();


    bus.emit(XinHeStorage.settingOrUpdateBankInfo);


  }


  setDefaultBank(XinHeBankEntity model) async{
    var userId =  await XinHeLocalStorage.get(XinHeStorage.userId);

    Map<String,dynamic>map = {
      'cardId':model.id,
      'userId':userId
    };
    XinHeRequestDataResult result = await XinHeHttpRequestData.requestUniversalPost(url: '/bankCard/setDefault',params: map,isPostAndwwwForm: true);

    if(!result.result|| result.data['code'] != 0){
      XinHeToast.center(result.data['message']);
      return ;
    }

    refreshData();

    XinHeToast.center('设置默认银行卡成功');

    bus.emit(XinHeStorage.settingOrUpdateBankInfo);

  }

  refreshData() {
    requestBanksInfo();
  }


}
